/*
 * PostLoad program for serial driver. 
 *
 * The function of this ditty is to ask the loaded driver what its
 * major number is, and to create the appropriate entries in /dev.
 */

#import <driverkit/IODeviceMaster.h>
#import "SccShared.h"
#import <libc.h>
#import <stdio.h>
#import <driverkit/IODevice.h>

#define DEBUG_LOG	0

#define NTTYSCC 2	// there are 4 in ttyscc.m, but we only make room
			//   for 2.
		
/*
 * A list of nodes to create. One per minor number, with a letter appended
 * to eaach indicating minor number. 
 */
typedef struct {
	const char *name;
	int minorNum;		/* in addition to 0..(NTTYSCC - 1) */
	int mode;
} ttyNode;

ttyNode nodeList[] = {
	{ "tty",	0,	(0666 | S_IFCHR) 	},
	{ "ttyf",	32,	(0666 | S_IFCHR)	}, 
	{ "ttyd",	64,	(0666 | S_IFCHR)	},
	{ "ttydf",	96,	(0666 | S_IFCHR)	},
	{ NULL,		0,	0			},	
};

int main(int argc, char **argv)
{
	id 		deviceMaster = [IODeviceMaster new];
	IOObjectNumber 	objectNum;
	IOString 	kind;
	IOReturn 	rtn;
	unsigned 	array[1];
	unsigned 	count = 1;
	int		minorNum;
	
	if(rtn = [deviceMaster lookUpByDeviceName:"com0"
		objectNumber:&objectNum
		deviceKind:&kind]) {
		fprintf(stderr, "Error contacting com0 (%s)\n",
			[IODevice stringFromReturn:rtn]);
		exit(1);	
	}
	rtn = [deviceMaster getIntValues : array
			   forParameter : SCC_CDEVSW_ENTRY
			   objectNumber : objectNum
			          count : &count];	// in/out
	if(rtn || (count != 1)) {
		fprintf(stderr, "Error performing %s (%s)\n",
			SCC_CDEVSW_ENTRY, [IODevice stringFromReturn:rtn]);
		exit(1);	
	}
	for(minorNum=0; minorNum<NTTYSCC; minorNum++) {
		char 		nodeName[20];
		ttyNode 	*node;
		char		minorLetter[2];
		int		dev;
		
		minorLetter[0] = 'a' + minorNum;
		minorLetter[1] = '\0';
		for(node=nodeList; node->name; node++) {
			sprintf(nodeName, "/dev/%s%s", 
				node->name, minorLetter);
			
			/*
			 * First delete existing node, then create a new one. 
			 */
			unlink(nodeName);
			dev = makedev(array[0], (node->minorNum + minorNum));
			if(mknod(nodeName, 
			    node->mode, 
			    dev)) {
				fprintf(stderr, "Can\'t create %s\n",
					nodeName);
			}
			if(DEBUG_LOG) {
				IOLog("Created %s\n", nodeName);
			}
		}
	}
	return 0;
}
